<script setup lang="ts">
defineOptions({
  name: "Servers"
});
import { copyDomText } from "@/utils/hide";
import { ref, reactive, onMounted, computed, watch } from "vue";
import {
  getServer,
  addServer,
  editServer,
  deleteServer,
  getServerStatus
} from "@/api/server";
import { message } from "@/utils/message";
import world from "@/assets/json/world.json";

onMounted(async () => {
  await getState();
});

const getState = async () => {
  let res = await getServer(
    currentPage.value,
    pageSize.value,
    search.value,
    server_type.value
  );
  let res2 = await getServer(
    currentPage.value,
    pageSize.value,
    search.value,
    "hyperV"
  );
  console.log("获取服务器列表", res.data.data, res2.data.data);
  tableData.value = res.data.data;
  total.value = res.data.count;
  regionsBuff.value = world;
  // 使用 Promise.all 等待所有请求完成
  res.data.data.forEach(item => {
    getServerStatus(item.server_id).then(res => {
      // 处理每个请求的结果
    });
  });

  res2.data.data.forEach(item => {
    getServerStatus(item.server_id).then(res => {
      // 处理每个请求的结果
    });
  });
};
// 获取列表
const getList = async () => {
  let res = await getServer(
    currentPage.value,
    pageSize.value,
    search.value,
    server_type.value
  );
  tableData.value = res.data.data;
  total.value = res.data.count;
  regionsBuff.value = world;
};
//搜索
const search = ref("");
const tableData = ref([]);
//新增还是修改
const addOrChange = ref(false);
const dialogOverflowVisible = ref(false);
//分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(20);
const handleCurrentPageChange = async newPage => {
  currentPage.value = newPage;
  console.log("切换页", currentPage.value);
  await getList();
};
const handlePageSizeChange = async newSize => {
  pageSize.value = newSize;
  await getList();
};

const form = reactive({
  server_id: "",
  name: "",
  server_ip: "",
  location: "",
  bandwidth: "",
  disk: "",
  memory: "",
  cpu: "",
  state: "",
  auth_id: "",
  server_token: "",
  server_type: "dockerContainer",
  html: "",
  hide: "",
  console_url: ""
});
// 数据格式改变
const locationArray = computed({
  get: () => {
    if (form.location) {
      const labels = form.location.split(" ");
      const values = labels.map(label =>
        findValueByLabel(label, regionsBuff.value)
      );
      return values.filter(value => value !== undefined);
    } else {
      return [];
    }
  },
  set: newArray => {
    if (Array.isArray(newArray) && newArray.length > 0) {
      const labels = newArray.map(value => {
        const label = findLabelByValue(value, regionsBuff.value);
        return label || value; // 如果找不到对应的 label，使用 value 作为 fallback
      });
      form.location = labels.join(" ");
    } else {
      form.location = "";
    }
  }
});
const findValueByLabel = (
  label: string,
  options: any[]
): string | undefined => {
  for (const option of options) {
    if (option.label === label) {
      return option.value;
    }
    if (option.children) {
      const result = findValueByLabel(label, option.children);
      if (result) {
        return result;
      }
    }
  }
  return undefined;
};

const findLabelByValue = (
  value: string,
  options: any[]
): string | undefined => {
  for (const option of options) {
    if (option.value === value) {
      return option.label;
    }
    if (option.children) {
      const result = findLabelByValue(value, option.children);
      if (result) {
        return result;
      }
    }
  }
  return undefined;
};

function show_table(data = null) {
  if (!data) {
    // 当data未传值，视为创建用户
    // 遍历form对象的每个键值对
    addOrChange.value = true;
    Object.keys(form).forEach(key => {
      form[key] = null;
    });
  } else {
    // data传值，视为修改
    // 遍历data对象的每个键值对
    addOrChange.value = false;
    console.log(data);
    Object.keys(data).forEach(key => {
      form[key] = data[key];
    });
  }
  if (server_type.value == "hyperV") {
    form.server_type = "hyperV";
  } else {
    form.server_type = "dockerContainer";
  }
}

// 删除用户
const handleDelete = async (index: number, row) => {
  console.log(row.server_id);

  let res = await deleteServer({ server_id: row.server_id });
  console.log("删除结果", res.data.code);

  if (res.data.code == 200) {
    //更新数据
    await getList();
    message("删除成功", { type: "success" });
  } else {
    message("删除失败！该数据关联了其他数据！", { type: "error" });
  }
};

// 提交数据
const onSubmit = async () => {
  console.log("submit!", form);
  if (addOrChange.value) {
    let res = await addServer(form);
    console.log("添加结果", res);
    dialogOverflowVisible.value = false;
  } else {
    let res = await editServer(form);
    console.log("编辑结果", res);
    dialogOverflowVisible.value = false;
  }
  //更新数据
  await getList();
  message("修改成功", { type: "success" });
};
//复制内容
const copytext = ref({});
const copyit = async () => {
  copytext.value = JSON.parse(JSON.stringify(form));
  copyDomText(JSON.stringify(copytext.value));
};
const getit = async () => {
  try {
    const text = await navigator.clipboard.readText();
    Object.keys(JSON.parse(text)).forEach(key => {
      form[key] = JSON.parse(text)[key];
    });
    message("粘贴成功", { type: "success" });
    return text;
  } catch (err) {
    message("无法读取剪贴板内容,请检查获取到的格式", { type: "error" });
  }
};
// 地图数据
const regionsBuff = ref([]);
// 定义选项配置
const optionProps = {
  label: "label",
  value: "value",
  children: "children"
};

// 计算当前设备的屏幕宽度
const dialogWidth = computed(() => {
  return window.innerWidth < 768 ? "350px" : "500px";
});

// 监听窗口大小变化
window.addEventListener("resize", () => {
  dialogWidth.value = window.innerWidth < 768 ? "350px" : "500px";
});
// 类型选择
const server_type = ref("dockerContainer");
watch(
  () => server_type.value,
  async (newVal, oldVal) => {
    if (newVal) {
      try {
        await getList();
      } catch (error) {
        console.error("获取数据失败：", error);
      }
    }
  }
);
</script>

<template>
  <div class="body">
    <div>
      <el-radio-group v-model="server_type" style="margin-bottom: 10px">
        <el-radio-button value="dockerContainer">容器云服务器</el-radio-button>
        <el-radio-button value="hyperV">虚拟机云服务器</el-radio-button>
      </el-radio-group>
    </div>
    <div class="table_box">
      <el-table class="table_el" :data="tableData" style="width: auto">
        <el-table-column label="ID" prop="server_id" show-overflow-tooltip />
        <el-table-column label="服务器名称" prop="name" show-overflow-tooltip />
        <el-table-column label="IP" prop="server_ip" show-overflow-tooltip />
        <el-table-column>
          <template #header>状态</template>
          <template #default="scope">
            <el-tag v-if="scope.row.state == 1" type="success">在线</el-tag>
            <el-tag v-if="scope.row.state == 0" type="danger">离线</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="购物车展示">
          <template #default="scope">
            <el-tag :type="scope.row.hide == 0 ? 'success' : 'danger'">
              {{ scope.row.hide == 0 ? "显示" : "隐藏" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column width="200">
          <template #header>
            <el-input v-model="search" size="small" placeholder="关键字筛选" />
          </template>
          <template #default="scope">
            <el-button size="small"
              ><router-link
                :to="
                  '/servers/server?server_id=' +
                  scope.row.server_id +
                  `&type=${server_type}`
                "
                >管理</router-link
              ></el-button
            >
            <el-button
              size="small"
              @click="
                show_table(scope.row);
                dialogOverflowVisible = true;
              "
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="table_pagination">
        <el-button
          type="primary"
          @click="
            show_table();
            dialogOverflowVisible = true;
          "
        >
          添加服务器
        </el-button>
        <el-pagination
          background
          layout="prev, pager, next,sizes"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @update:current-page="handleCurrentPageChange"
          @update:page-size="handlePageSizeChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogOverflowVisible"
      title="服务器信息"
      :width="dialogWidth"
      draggable
      overflow
    >
      <div>
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="服务器名称" required>
            <el-input
              v-model="form.name"
              placeholder="请输入服务器名称"
              required
            />
          </el-form-item>
          <el-form-item label="IP" required>
            <el-input
              v-model="form.server_ip"
              placeholder="请输入服务器IP"
              required
            />
          </el-form-item>
          <el-form-item label="地区">
            <el-cascader
              v-model="locationArray"
              :options="regionsBuff"
              :props="optionProps"
              placeholder="请选择位置"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="带宽">
            <el-input v-model="form.bandwidth" placeholder="服务器带宽/mbps" />
          </el-form-item>
          <el-form-item label="允许分配硬盘">
            <el-input v-model="form.disk" placeholder="硬盘大小/GB" />
          </el-form-item>
          <el-form-item label="允许分配内存">
            <el-input v-model="form.memory" placeholder="内存大小/GB" />
          </el-form-item>
          <el-form-item label="允许分配CPU">
            <el-input v-model="form.cpu" placeholder="cpu大小/核" />
          </el-form-item>
          <el-form-item label="类型选项">
            <el-radio-group v-model="form.server_type">
              <el-radio-button value="dockerContainer"
                >容器云服务器</el-radio-button
              >
              <el-radio-button value="hyperV">虚拟机云服务器</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.server_type === 'dockerContainer'"
            label="Auth-ID"
          >
            <el-input
              v-model="form.auth_id"
              placeholder="节点服务器管理员的auth_id"
            />
          </el-form-item>
          <el-form-item label="Token">
            <el-input
              v-model="form.server_token"
              placeholder="节点服务器管理员的token"
            />
          </el-form-item>
          <el-form-item label="展示卡片">
            <el-input v-model="form.html" placeholder="购买展示卡片的样式" />
          </el-form-item>
          <el-form-item label="控制台连接接口">
            <el-input
              v-model="form.console_url"
              placeholder="若使用https协议则必须进行反向代理，默认可不填写"
            />
          </el-form-item>
          <el-form-item label="购物车显示">
            <el-radio-group v-model="form.hide">
              <el-radio-button :value="1">隐藏</el-radio-button>
              <el-radio-button :value="0">显示</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="getit">一键粘贴内容</el-button>
          <el-button @click="copyit">一键复制内容</el-button>
          <el-button
            style="margin-bottom: 5px"
            @click="dialogOverflowVisible = false"
            >关闭</el-button
          >
          <el-button type="primary" @click="onSubmit"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.table_box {
  display: flex;
  flex-direction: column;
  height: 50%;
}

.table_box .table_el {
  flex: 1;
}

.table_pagination {
  background-color: #fff;
  padding: 8px 30px;
  display: flex;
  justify-content: space-between;
}
</style>
